#include "maininterfacewidget.h"
#include "ui_maininterfacewidget.h"
#include "user.h"
#include "addfriendsender.h"
#include "addfriendreceiver.h"
#include "addfriendsearch.h"
#include "friendlist.h"

MainInterfaceWidget::MainInterfaceWidget(QWidget *parent, user userSelf)
    : QWidget(parent)
    , ui(new Ui::MainInterfaceWidget)
{
    ui->setupUi(this);
    //connect()
    //qDebug() << "userSelf:" << userSelf.getUserName();
    //websocket传输代码
    this->userSelf = userSelf;
    socket = new QWebSocket();//新建websocket
    QUrl url("ws://101.43.168.188:19999/slimarveous/ws");
    QUrlQuery query;//在query里面添加id token两个信息
    query.addQueryItem("id",userSelf.getUserId());
    query.addQueryItem("token",userSelf.getUserPassword());
    url.setQuery(query);
    socket->open(url);
    //连接到server
    QObject::connect(socket, &QWebSocket::connected,[=]()
    {
        qDebug() << "WebSocket connected";
    });
    //断开链接
    QObject::connect(socket, &QWebSocket::disconnected, [=]()
    {
        qDebug() << "WebSocket disconnected";
    });
    //获取信息
    QObject::connect(socket, &QWebSocket::textMessageReceived, [=](const QString &message)
    {
        //qDebug() << "Received message:" << message;
        //接收信息
        QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
        //doc转换成json
        QJsonObject obj = doc.object();
        //分析接收到的服务器信息类型
        QString type = obj.value("type").toString();//传到服务器后端的类型type参数
        //类型为chat
        if (type == "chat")
        {
            QVariantMap messageMap = obj.toVariantMap();
            QMap senderMap = messageMap.value("sender").toMap();
            QVariant senderName = senderMap.value("username");
            QString receivedContent = obj.value("content").toString();
            QString receivedTime = obj.value("time").toString();
            ui->dialogTextBrowser->append(receivedTime+" "+senderName.toString()+":");
            ui->dialogTextBrowser->append("<font color = 'black' size = 24px>" + receivedContent + "</font>");//对话框中添加信息
            //对话双方均在线直接显示
        }
        //类型为未读消息
        else if (type == "pull_chat")
        {
            //将未读消息json文件转化成map
            QVariantMap pullChatMap = obj.toVariantMap();
            QJsonArray ucMsg = pullChatMap.value("uc_messages").toJsonArray();
            for(int i = 0; i < ucMsg.size(); i++)
            {
                QJsonObject ucJsonObj = ucMsg.at(i).toObject();
                QVariantMap messageMap = ucJsonObj.toVariantMap();
                QMap senderMap = messageMap.value("sender").toMap();
                QVariant senderName = senderMap.value("username");
                QString ucMsgContent = ucJsonObj.value("content").toString();
                QString ucMsgTime = ucJsonObj.value("time").toString();
                ui->dialogTextBrowser->append(ucMsgTime+" "+senderName.toString()+":");
                ui->dialogTextBrowser->append("<font color = 'black' size = 24px>" + ucMsgContent + "<></font>");
                //对话框中添加信息

            }

        }
        else if (type == "add_friend")
        {
            addfriendreceiver *afr = new addfriendreceiver(nullptr, userSelf);
            afr->show();
        }
        else if (type=="add_friend_fail_or_success")
        {
            QVariantMap messageMap = obj.toVariantMap();
            QMap receiverMap = messageMap.value("the_other").toMap();
            QVariant receiverName = receiverMap.value("username");
            QString add_friend_fail_or_success=obj.value("add_friend_fail_or_success").toString();
            QString message=obj.value("message").toString();
            QMessageBox:: information(this, "你向"+receiverName.toString()+"好友请求",message);
        }
    });
    connect(ui->addfriendsender,&QPushButton::clicked,this, &MainInterfaceWidget::addfriendsender_clicked);
    connect(ui->addfriendsearch,&QPushButton::clicked,this, &MainInterfaceWidget::addfriendsearch_clicked);
    connect(ui->friendlist,&QPushButton::clicked,this, &MainInterfaceWidget::friendlist_clicked);
}

MainInterfaceWidget::~MainInterfaceWidget()
{
    delete ui;
}


void MainInterfaceWidget::on_btn_send_main_clicked()
{
    //Sender创建
    UserBrief Sender;
    Sender = {
        userSelf.getUserId(),//id
        userSelf.getUserName(),//username
        "",//photo
        userSelf.getUserGender()//gender
    };
    QDateTime currentTime = QDateTime::currentDateTime(); // 获取当前时间
    int year = currentTime.date().year(); // 获取年份
    int month = currentTime.date().month(); // 获取月份
    int day = currentTime.date().day();     // 获取日期
    int hour = currentTime.time().hour();   // 获取小时
    int minute = currentTime.time().minute(); // 获取分钟
    QString time = QString::number(year) + "-" + QString::number(month) + "-"
            + QString::number(day) + " " + QString::number(hour) + ":" + QString::number(minute);
    //get content
    QString sendContent = ui->messageSendTextEdit->toPlainText();//传输服务器
    QString receiverId = ui->receiverId->text();
    receiverId.toLongLong();//id转化为long long
    //connect to server
    //sender信息
    QJsonObject senderValue
    {
        {"id", Sender.id.toInt()},
        {"username", Sender.username},
        {"photo", ""},
        {"gender", Sender.gender.toInt()}
    };
    //receiver信息
    QJsonObject receiverValue
    {
        {"id", receiverId.toInt()},
        {"username", ""},
        {"photo", ""},
        {"gender", 1}
    };
    //发送的信息
    QJsonObject json{
        {"sender",senderValue},
        {"receiver", receiverValue},
        {"time", time},
        {"type", "chat"},
        {"content", sendContent},
        {"is_photo","0"}
    };
    QJsonDocument doc(json);
    QByteArray data = doc.toJson(QJsonDocument::Compact);
    socket->sendTextMessage(data);
    ui->dialogTextBrowser->append(time + " me:");
    ui->dialogTextBrowser->append("<font color = 'black' size = 24px>" + sendContent + "</font>");
    ui->messageSendTextEdit->clear();
}
void MainInterfaceWidget::on_btn_clear_main_clicked()
{
    ui->messageSendTextEdit->clear();
}

void MainInterfaceWidget::addfriendsender_clicked()
{
    addfriendsender *afs = new addfriendsender(nullptr, userSelf);
    afs->show();
}
void MainInterfaceWidget:: addfriendreceiver_clicked()
{
    addfriendreceiver *afr = new addfriendreceiver(nullptr, userSelf);
    afr->show();
}
void MainInterfaceWidget:: addfriendsearch_clicked()
{
    addfriendsearch *afsr = new addfriendsearch(nullptr, userSelf);
    afsr->show();
}
void MainInterfaceWidget:: friendlist_clicked()//好友列表
{
    friendlist *fl = new friendlist(nullptr, userSelf);
    fl->show();
}
